﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using UnityEngine;

namespace HEFramework
{
    /// <summary>
    ///
    /// Unity公共单元类
    /// 
    /// ----------------------------------------
    /// 作者 hep
    /// 创建时间：2023-12-19 20:20:31
    /// ----------------------------------------
    /// </summary>
    public static class UnityUtility
    {
        #region 格式化相关

        /// <summary>
        /// 转换路径
        /// </summary>
        /// <param name="_str"></param>
        /// <returns></returns>
        public static string RB(this string _str)
        {
            return _str.Replace("\\", "/");
        }

        /// <summary>
        /// 去除生成对象(Clone)后缀
        /// </summary>
        /// <param name="_gameObject"></param>
        public static string RS(this GameObject _gameObject)
        {
#if UNITY_EDITOR
            if (_gameObject == null)
            {
                return null;
            }

            if (_gameObject.name.Contains("(Clone)"))
            {
                _gameObject.name = _gameObject.name.Replace("(Clone)", "");
            }
#endif
            return _gameObject.name;
        }

        /// <summary>
        /// 颜色代码转化成Color
        /// </summary>
        /// <param name="_code"></param>
        /// <returns></returns>
        public static Color Code2RGB(this string _code)
        {
            char[] rgb = _code.ToCharArray();
            int red = Convert.ToInt32(rgb[0].ToString() + rgb[1].ToString(), 16);
            int green = Convert.ToInt32(rgb[2].ToString() + rgb[3].ToString(), 16);
            int blue = Convert.ToInt32(rgb[4].ToString() + rgb[5].ToString(), 16);
            return new Color(red / 255f, green / 255f, blue / 255f);
        }

        /// <summary>
        /// 获取颜色
        /// </summary>
        /// <param name="_r"></param>
        /// <param name="_g"></param>
        /// <param name="_b"></param>
        /// <param name="_a"></param>
        /// <returns></returns>
        public static Color Color(float _r = 255f, float _g = 255f, float _b = 255f, float _a = 1)
        {
            const float scale = 1.0f / 255.0f;
            return new Color(_r * scale, _g * scale, _b * scale, _a);
        }

        /// <summary>
        /// 对象序列化（byte）
        /// </summary>
        /// <param name="_value"></param>
        /// <returns></returns>
        public static byte[] Encode(this object _value)
        {
            //创建编码解码的内存流对象
            MemoryStream ms = new MemoryStream();
            //二进制流序列化对象
            BinaryFormatter bw = new BinaryFormatter();
            //将obj对象序列化成二进制数据 写入到 内存流                         
            bw.Serialize(ms, _value);
            byte[] result = new byte[ms.Length];
            //将流数据 拷贝到结果数组
            System.Buffer.BlockCopy(ms.GetBuffer(), 0, result, 0, (int)ms.Length);
            ms.Close();
            return result;
        }

        /// <summary>
        /// 反序列化为对象（byte）
        /// </summary>
        /// <param name="_value"></param>
        /// <returns></returns>
        public static object Decode(this byte[] _value)
        {
            //创建编码解码的内存流对象 并将需要反序列化的数据写入其中
            MemoryStream ms = new MemoryStream(_value);
            //二进制流序列化对象
            BinaryFormatter bw = new BinaryFormatter();
            //将流数据反序列化为obj对象                          
            object result = bw.Deserialize(ms);
            ms.Close();
            return result;
        }

        #endregion


        #region Unity组件功能相关

        /// <summary>
        /// 设置某对象以及子对象层级
        /// </summary>
        /// <param name="_gameObject"></param>
        /// <param name="_layerName">层级名称</param>
        public static void SetLayers(this GameObject _gameObject, string _layerName)
        {
            Transform[] transforms = _gameObject.GetComponentsInChildren<Transform>(true);
            for (int i = 0; i < transforms.Length; i++)
            {
                transforms[i].gameObject.layer = LayerMask.NameToLayer(_layerName);
            }
        }


        /// <summary>
        ///  设置物体local坐标
        /// </summary>
        /// <param name="_gameObject"></param>
        /// <param name="_position"></param>
        public static void SetLocalPosition(this GameObject _gameObject, Vector3 _position)
        {
            _gameObject.transform.localPosition = _position;
        }


        /// <summary>
        /// 设置物体local旋转角度
        /// </summary>
        /// <param name="_gameObject"></param>
        /// <param name="_rotate"></param>
        public static void SetLocalEulerAngles(this GameObject _gameObject, Vector3 _rotate)
        {
            _gameObject.transform.localEulerAngles = _rotate;
        }

        /// <summary>
        /// 角度转换向量
        /// </summary>
        /// <param name="_angle"></param>
        /// <returns></returns>
        public static Vector2 AngleToDirection(this float _angle)
        {
            // 角度转换为弧度
            float angleInRadians = _angle * Mathf.Deg2Rad;

            // 计算朝向的向量
            Vector2 direction = new Vector2(Mathf.Cos(angleInRadians), Mathf.Sin(angleInRadians));

            return direction;
        }

        #endregion


        #region 其他

        public static void CheckFunTime(Action _callback)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            _callback?.Invoke();
            sw.Stop();
            TimeSpan ts = sw.Elapsed;
            UnityEngine.Debug.Log(ts);
        }

        #endregion
    }
}